/**
 * JWT解析工具类
 */

// Base64URL解码
const base64UrlDecode = (str) => {
    // 将Base64URL转换为Base64
    let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
    // 添加填充字符
    while (base64.length % 4) {
        base64 += '=';
    }
    // 解码
    try {
        return decodeURIComponent(escape(atob(base64)));
    } catch (e) {
        return atob(base64);
    }
};

// 解析JWT Token
export const parseJwt = (token) => {
    try {
        // 分割token
        const parts = token.split('.');
        if (parts.length !== 3) {
            throw new Error('Invalid JWT format');
        }

        // 解析header和payload
        const header = JSON.parse(base64UrlDecode(parts[0]));
        const payload = JSON.parse(base64UrlDecode(parts[1]));

        return {
            header,
            payload,
            signature: parts[2]
        };
    } catch (error) {
        console.error('JWT parsing error:', error);
        return null;
    }
};

// 检查token是否过期
export const isTokenExpired = (token) => {
    try {
        const { payload } = parseJwt(token);
        if (!payload || !payload.exp) {
            return true;
        }
        // exp是以秒为单位的时间戳
        return payload.exp * 1000 < Date.now();
    } catch (error) {
        console.error('Token expiration check error:', error);
        return true;
    }
}; 